<template>
  <div class="container">
    <el-card :style="{maxHeight: contentHeight * 0.8 + 'px'}" class="box-card">
      <div class="title">卡修改</div>
      <el-form ref="dataFormRef" :model="dataForm" label-width="120px" style="padding: 30px;" @submit.native.prevent>
        <el-alert :closable="false" class="alert-info" show-icon style="margin-bottom: 15px;" title="输入验证信息手机号或卡号"
                  type="info"/>
        <el-row :gutter="30">
          <el-col :span="10">
            <el-form-item label="手机或卡号：" prop="phone">
              <el-input v-model="dataForm.phone" clearable placeholder="请输入手机号码或卡号" @keyup.enter.native="getCardList"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button circle icon="el-icon-search" type="primary" @click="getCardList"/>
          </el-col>
        </el-row>
        <el-alert :closable="false" class="alert-info" show-icon style="margin-bottom: 15px;" title="选择对应的记录，执行对应操作"
                  type="info"/>
        <el-table :data="cardList" border height="300" size="small" style="width: 100%;">
          <el-table-column align="center" label="类型" prop="cardNo">
            <template slot-scope="scope">
              <span>{{ scope.row.masterUid ? '副卡' : '主卡' }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="卡号" prop="cardNo"/>
          <el-table-column align="center" label="姓名" prop="username"/>
          <el-table-column align="center" label="卡名称" prop="cardName"/>
          <el-table-column align="center" label="会员ID" prop="memberId"/>
          <el-table-column align="center" label="账户余额" prop="balance"/>
          <el-table-column align="center" label="操作" width="400px">
            <template slot-scope="scope">
              <el-button size="mini" type="warning" @click="handleCardInfoUpdate(scope.row)">编辑</el-button>
              <el-button v-if="scope.row.cardStatus !== -1" size="mini"
                         type="warning" @click="handleCardLock(scope.row)">挂失
              </el-button>
              <el-button v-if="scope.row.cardStatus == -1" size="mini"
                         type="primary" @click="handleCardUnlock(scope.row)">解挂失
              </el-button>
              <el-button v-if="!scope.row.memberId" :disabled="!!scope.row.masterUid" size="mini" type="primary"
                         @click="handleMemberBind(scope.row)">绑定
              </el-button>
              <el-button v-if="scope.row.memberId" :disabled="!!scope.row.masterUid" size="mini" type="warning"
                         @click="handleMemberUnbind(scope.row)">解绑
              </el-button>
              <el-button size="mini" type="danger" @click="handleWriteCard(scope.row)">写卡</el-button>
              <el-button size="mini" type="danger" @click="handleChangeCardNo(scope.row)">换卡</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn-bar">
          <el-button icon="el-icon-s-open" round size="small" style="float:left;" type="primary" @click="initCard">
            卡初始化
          </el-button>
          <el-button round size="small" type="primary" @click="handleReadCardNo">识别卡</el-button>
        </div>
      </el-form>
    </el-card>
    <div class="home-btn">
      <div class="btn-item">
        <el-button icon="el-icon-back" round size="small" type="primary" @click="goBackHome"> 返 回</el-button>
      </div>
      <div class="btn-item">
        <el-button icon="el-icon-search" round size="small" type="info" @click="goCardInfo">卡查询</el-button>
      </div>
    </div>
    <el-dialog :visible.sync="detailVisible" height="70%" title="修改" width="70%">
      <div style="height:300px;margin-top: 10px;margin-right: 30px">
        <el-form ref="form" :model="checkForm" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="用户姓名：">
                <el-input v-model="checkForm.username"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="用户电话：">
                <el-input v-model="checkForm.phone"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="车牌号码：">
                <el-input v-model="checkForm.carNumber"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="开票类型">
                <el-select v-model="checkForm.invoiceType" :disabled="!!checkForm.masterUid">
                  <el-option :value="1" label="消费开票"/>
                  <el-option :value="2" label="充值开票"/>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="24">
              <el-form-item label="可用油品：">
                <el-checkbox-group v-model="usableFuelList">
                  <el-checkbox label="0#"></el-checkbox>
                  <el-checkbox label="92#"></el-checkbox>
                  <el-checkbox label="95#"></el-checkbox>
                  <el-checkbox label="98#"></el-checkbox>
                </el-checkbox-group>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div style="margin-left: 30px;text-align: right;">
          <el-button round type="success" @click="updateCardInfo"> 确 定</el-button>
          <el-button v-show="!checkForm.masterUid" :disabled="!!checkForm.masterUid" round type="danger"
                     @click="handleUpdateCardPassword(checkForm)">修改主卡密码
          </el-button>
          <el-button v-show="checkForm.masterUid" :disabled="!checkForm.masterUid" round type="danger"
                     @click="handleUpdateCardSecondPassword(checkForm)">修改副卡密码
          </el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {mapGetters} from 'vuex'
import {
  addWriteCardRecord,
  bindMember,
  changeCardNo,
  getWriteCardRecords,
  masterCardListByPhone,
  masterReportLost,
  masterUndoReportLost,
  masterUpdateCardInfo,
  secondCardListByPhone,
  secondReportLost,
  secondUndoReportLost,
  secondUpdateCardInfo,
  unbindMember,
  updateCardPassword,
  updateCardSecondPassword
} from '@/api/card'
import {getMemberInfoByOpenid} from '@/api/member'
import {initCard, isEmptyCard, isNewEmptyCard, readCardNo, writeCardNo} from '@/utils/cardreader'

export default {
  name: 'CardLock',
  data () {
    return {
      dataForm: {
        idCardNo: '',
        phone: ''
      },
      dataList: [],
      secondCardList: [], // 副卡列表
      stationList: [],
      detailVisible: false,
      checkForm: {},
      usableFuelList: []
    }
  },
  computed: {
    ...mapGetters(['contentHeight', 'operator', 'stationId', 'stationName', 'shiftName']),
    cardList () {
      return this.dataList.concat(this.secondCardList)
    }
  },
  methods: {
    goBackHome () {
      this.$router.push('/card')
    },
    goCardInfo () {
      this.$router.push('/card/info')
    },
    handleCardLock (rowData) {
      console.log('handleCardLock')
      console.log(rowData)
      this.$confirm('是否确定要挂失？', '提示', {type: 'warning'}).then(() => {
        var isSecond = !!rowData.masterUid
        if (isSecond) {
          secondReportLost({uid: rowData.uid, masterUid: rowData.masterUid}).then(res => {
            console.log('secondReportLost')
            console.log(res)
            this.$message.success(res.msg || '副卡挂失成功')
            this.getCardList()
          })
        } else {
          masterReportLost({uid: rowData.uid}).then(res => {
            console.log('masterReportLost')
            console.log(res)
            this.$message.success(res.msg || '主卡挂失成功')
            this.getCardList()
          })
        }
      })
    },
    handleCardUnlock (rowData) {
      console.log('handleCardUnlock')
      console.log(rowData)
      this.$confirm('是否确定解除挂失？', '提示', {type: 'warning'}).then(() => {
        var isSecond = !!rowData.masterUid
        if (isSecond) {
          secondUndoReportLost({uid: rowData.uid, masterUid: rowData.masterUid}).then(res => {
            console.log('secondUndoReportLost')
            console.log(res)
            this.$message.success(res.msg || '副卡解除挂失成功')
            this.getCardList()
          })
        } else {
          masterUndoReportLost({uid: rowData.uid}).then(res => {
            console.log('masterUndoReportLost')
            console.log(res)
            this.$message.success(res.msg || '解除挂失成功')
            this.getCardList()
          })
        }
      })
    },
    getCardList () {
      masterCardListByPhone({phone: this.dataForm.phone}).then(res => {
        console.log(res)
        this.dataList = res.data
      }).catch(err => {
        console.log(err)
        this.dataList = []
        this.$message.error(err || '操作失败')
      })
      secondCardListByPhone({phone: this.dataForm.phone}).then(res => {
        console.log(res)
        this.secondCardList = res.data
      }).catch(err => {
        console.log(err)
        this.secondCardList = []
        this.$message.error(err || '操作失败')
      })
    },
    // 会员绑定
    handleMemberBind (rowData) {
      if (rowData.cardType === 5) {
        this.$message.warning('不记名优惠卡不允许绑定会员！')
        return false
      }
      this.$prompt('扫描顾客会员码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password',
        inputErrorMessage: '储值卡号码格式不正确'
      }).then(({value}) => {
        console.log(value)
        if (value) {
          // 根据会员码获取会员id，然后根据会员id和加油卡uid调用会员绑定接口
          getMemberInfoByOpenid(value).then(res => {
            console.log(res)
            bindMember({uid: rowData.uid, memberId: res.data.id}).then(res => {
              console.log(res)
              this.$message.success(res.msg || '会员绑定成功')
              this.getCardList()
            }).catch(err => {
              console.log(err)
            })
          }).catch(err => {
            console.log(err)
            this.$message.warning('会员码不正确')
          })
        }
      }).catch(() => {
        console.log('cancel')
      })
    },
    // 会员解绑
    handleMemberUnbind (rowData) {
      this.$confirm('确定解绑会员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        unbindMember({uid: rowData.uid}).then(res => {
          console.log(res)
          this.$message.success(res.msg || '解绑成功')
          this.getCardList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        console.log('cancel')
      })
    },
    // 编辑
    handleCardInfoUpdate (rowData) {
      this.checkForm = rowData
      console.log(this.checkForm)
      this.usableFuelList = rowData.usableFuelNames.split(',')
      this.detailVisible = true
    },
    // 提交表单
    updateCardInfo () {
      // 校验值是否为空
      if (Number(this.checkForm.phone) === 0) {
        this.$message.warning('手机号不得为空')
        return false
      }
      if (this.usableFuelList.length === 0) {
        this.$message.warning('可用油品不得为空')
        return false
      }
      this.$confirm('确定更改卡信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 转为String后再去发请求
        this.checkForm.usableFuelNames = this.usableFuelList.toString()
        if (!this.checkForm.masterUid) {
          console.log('主卡更新')
          masterUpdateCardInfo(this.checkForm).then(res => {
            this.$message.success(res.msg || '更改成功')
            this.getCardList()
            this.detailVisible = false
          }).catch(err => {
            this.$message.error(err)
            console.log(err)
          })
        } else {
          console.log('副卡更新')
          secondUpdateCardInfo(this.checkForm).then(res => {
            this.$message.success(res.msg || '更改成功')
            this.getCardList()
            this.detailVisible = false
          }).catch(err => {
            this.$message.error(err)
            console.log(err)
          })
        }
      }).catch(() => {
        console.log('cancel')
      })
    },
    handleWriteCard (rowData) {
      console.log(rowData)
      // 判断卡片是否合法的空白卡
      var ok = isEmptyCard()
      if (!ok) {
        this.$message.warning('该卡不是空白卡或尚未初始化')
        return false
      }
      // 请求获取该卡号的写卡记录
      getWriteCardRecords(rowData.cardNo).then(res => {
        if (res.data.length > 0) {
          this.$message.error('该卡号已执行过写卡操作，无法继续写卡！！!')
          return false
        }
        // 提示是否确定要执行该操作
        this.$confirm('确定把卡号[' + rowData.cardNo + ']写入到卡片上, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 执行写卡操作
          // 验证卡号是否匹配
          // 提示操作结果
          writeCardNo(rowData.cardNo)
          var cardNo = readCardNo()
          if (cardNo === rowData.cardNo) {
            this.$message.success('写卡成功！' + cardNo)
            // 记录写卡操作
            addWriteCardRecord({
              stationId: this.stationId,
              operator: this.operator,
              cardNo: cardNo,
              cardUid: rowData.uid
            })
          }
        }).catch(() => {
          console.log('cancel')
        })
      }).catch(err => {
        console.log(err)
        this.$message.error('获取写卡记录失败，请联系管理员！')
      })
    },
    handleUpdateCardPassword (rowData) {
      this.detailVisible = false
      console.log(rowData)
      this.$prompt('请输入6位数字的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password'
      }).then(({value}) => {
        // 判断是不是6位数字密码
        if (value.length !== 6 || isNaN(value)) {
          this.$message.error('请输入6位数字的密码!')
          return false
        }
        rowData.password = value
        this.$prompt('请再次确认密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'password'
        }).then(({value}) => {
          if (value === rowData.password) {
            console.log(value)
            updateCardPassword({
              uid: rowData.uid,
              password: value,
              id: rowData.id
            }).then(res => {
              this.$message.success(res.msg || '密码修改成功')
            }).catch(err => {
              console.log(err)
              this.$message.error(err)
            })
          } else {
            this.$message.error('两次输入的密码不一样!')
            this.handleUpdateCardPassword(rowData)
          }
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
    handleUpdateCardSecondPassword (rowData) {
      this.detailVisible = false
      console.log(rowData)
      this.$prompt('请输入6位数字的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'password'
      }).then(({value}) => {
        // 判断是不是6位数字密码
        if (value.length !== 6 || isNaN(value)) {
          this.$message.error('请输入6位数字的密码!')
          return false
        }
        rowData.password = value
        this.$prompt('请再次确认密码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputType: 'password'
        }).then(({value}) => {
          if (value === rowData.password) {
            console.log(value)
            updateCardSecondPassword({
              uid: rowData.uid,
              password: value,
              id: rowData.id
            }).then(res => {
              this.$message.success(res.msg || '密码修改成功')
            }).catch(err => {
              console.log(err)
              this.$message.error(err)
            })
          } else {
            this.$message.error('两次输入的密码不一样!')
            this.handleUpdateCardSecondPassword(rowData)
          }
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
    handleChangeCardNo (rowData) {
      console.log('handleChangeCardNo')
      console.log(rowData)
      // 先检查是否读卡器上是否有一张初始化好的空白卡
      // 判断卡片是否合法的空白卡
      var ok = isEmptyCard()
      if (!ok) {
        this.$message.warning('该卡不是空白卡或尚未初始化')
        return false
      }
      // 弹窗提示输入新卡卡号后缀，9位长度，不足前面补0
      this.$prompt('请输入9位新卡编号，不足9位前面补0', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputType: 'text'
      }).then(({value}) => {
        console.log(value)
        // 长度是否足够，是否都为数字
        if (value.length !== 9) {
          this.$message.error('新卡编号长度必须为9位！')
          return false
        }
        if (isNaN(value)) {
          this.$message.error('新卡编号必须是数字')
          return false
        }
        // 调用换卡接口，成功后把返回对象中的卡号写入到空白卡中
        changeCardNo({
          uid: rowData.uid,
          cardNo: value,
          operator: this.operator
        }).then(res => {
          console.log('changeCardNo')
          console.log(res)
          this.$message.success(res.msg || '换卡成功！')
          let cardInfo = res.data
          writeCardNo(cardInfo.cardNo)
          var cardNo = readCardNo()
          if (cardNo === cardInfo.cardNo) {
            this.$message.success('写卡成功！' + cardNo)
            this.getCardList()
          }
        }).catch(err => {
          console.log(err)
          this.$message.error(err || '换卡失败！')
        })
      })
    },
    handleReadCardNo () {
      var cardNo = readCardNo()
      if (cardNo) {
        this.dataForm.phone = cardNo
        this.getCardList()
      } else {
        this.$message.warning('没有识别到卡号！')
      }
    },
    initCard () {
      console.log('initCard')
      var err = isNewEmptyCard()
      if (err) {
        this.$message.warning('该卡不是有效的空白卡')
        return false
      }
      err = initCard()
      if (err) {
        this.$message.error('卡初始化失败')
        return false
      }
      this.$message.success('卡初始化成功！')
    }
  }
}
</script>

<style scoped>
.el-select {
  width: 100%;
}

.box-card {
  width: 60%;
  margin-left: 20%;
  position: absolute;
  top: 4%;
  overflow-y: auto;
}

.btn-bar {
  margin-top: 20px;
  text-align: right;
}

.home-btn {
  position: absolute;
  top: 2%;
  left: 2%;
}

.btn-item {
  margin-bottom: 20px;
}

.title {
  text-align: center;
  padding-top: 1%;
  font-size: 1.6rem;
  color: #666;
}

.card-form {
  background: white;
  padding: 20px;
}
</style>
